package com.luohoufa.ms.order.message;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.luohoufa.ms.product.common.ProductInfoOutput;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.List;

@Component
@Slf4j
public class ProductInfoReceiver {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public static final String PRODUCT_STOCK = "productStock_%s";

    @RabbitListener(queuesToDeclare=@Queue("productInfo"))
    public void process(String message) {
        Type type = new TypeToken<List<ProductInfoOutput>>(){}.getType();
        List<ProductInfoOutput> productInfoOutputList = new Gson().fromJson(message, type);
        log.info("product={}", productInfoOutputList);

        for (ProductInfoOutput productInfoOutput : productInfoOutputList) {
            // 存到Redis中
            stringRedisTemplate.opsForValue()
                    .set(String.format(PRODUCT_STOCK, productInfoOutput.getProductId()),
                            String.valueOf(productInfoOutput.getProductStock()));
        }

    }

}
